using System;
using System.Collections.Generic;
using System.Text;
using Jbe.TestSuite.Infrastructure.Interface;
using Jbe.TestSuite.TestDevice.Manager.Interface.Services;
using Jbe.TestSuite.TestDevice.FunctionGen.Driver.Services;
using Microsoft.Practices.CompositeUI;
using Microsoft.Practices.CompositeUI.Commands;
using Jbe.TestSuite.TestDevice.FunctionGen.Driver.Constants;
using Jbe.TestSuite.TestDevice.FunctionGen.Interface.Services;

namespace Jbe.TestSuite.TestDevice.FunctionGen.Driver
{
    public class InstanceController : WorkItemController, IDevice
    {
        public event EventHandler Disconnected;

        private ITestDeviceManager testDeviceManager;
        private FunctionGenDriver functionGen;

        [ServiceDependency]
        public ITestDeviceManager TestDeviceManager
        {
            set { testDeviceManager = value; }
        }

        public string ProfileName
        {
            get { return ProfileNames.FunctionGenerator; }
        }

        public string ProductName
        {
            get { return "Virtual Function Generator"; }
        }

        public string Manufacturer
        {
            get { return "jbe"; }
        }

        public override void Run()
        {
            WorkItem.Services.Add<IDevice>(this);
            functionGen = WorkItem.Services.AddNew<FunctionGenDriver, IFunctionGen>();
            WorkItem.Disposed += new EventHandler(WorkItemDisposed);

            testDeviceManager.Register(this);
        }

        public void Disconnect()
        {
            testDeviceManager.Deregister(this);
            OnDisconnected();
            if (WorkItem.Status != WorkItemStatus.Terminated) { WorkItem.Terminate(); }
        }

        protected virtual void OnDisconnected()
        {
            if (Disconnected != null) { Disconnected(this, new EventArgs()); }
        }

        private void WorkItemDisposed(object sender, EventArgs e)
        {
            Disconnect();
        }
    }
}
